<template>
  <div>
    <Dialog
      v-model="showDialog"
      :title="`选择分组`"
      :width="500"
      @confirm="submitForm"
      @close="cancel"
      @open="openDialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        label-position="top"
      >
        <el-form-item label="分组" prop="nodeId">
          <TreeSelect
            class="_tree_select"
            v-model="form.nodeId"
            :treeSelectData="treeSelectData"
            :treeProps="{
              label: 'name',
              disabled: (data: any) => {
                return Boolean(data.nodeType && !data.children);
              },
            }"
            placeholder="请选择分组"
          ></TreeSelect>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import CustomerApi from "@/api/customerApi";
const props = withDefaults(
  defineProps<{
    showDialog: boolean;
    selectionList: string[];
  }>(),
  {}
);
const { showDialog, selectionList } = toRefs(props);
const formRef = ref();
const treeSelectData = ref([] as any);
const form = ref({
  nodeId: "" as string | number,
} as any);
const rules = ref({
  nodeId: [{ required: true, message: "请选择分组", trigger: "blur" }],
});

const openDialog = async () => {
  let rs = await CustomerApi.getCustomersGroupTree({});
  if (rs.code === 200) {
    treeSelectData.value = rs.payload;
  }
};

const submitForm = async () => {
  await formRef.value.validate((valid: any) => {
    if (valid) {
      updateCategoryBatch();
    }
  });
};

const updateCategoryBatch = async () => {
  let params = {
    categoryId: form.value.nodeId,
    userGroupIds: selectionList.value.map((item: any) => item.id),
  };
  let rs = await CustomerApi.updateCategoryBatch(params);
  if (rs.code === 200) {
    ElMessage.success(`修改成功`);
    confirm();
  }
};

const confirm = () => {
  emit("confirm", form.value.nodeId);
  cancel();
};
const cancel = () => {
  emit("cancel");
  formRef.value.resetFields();
  form.value = {
    nodeId: "",
  };
};
const emit = defineEmits(["confirm", "cancel"]);
</script>
<style lang="scss" scoped>
._tree_select {
  width: 100%;
}
</style>
